# -*- coding:utf-8 -*-
# -------------------------------数据库配置--------------------------------
import datetime
import os
import redis
from flask_admin import Admin
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from flask_session import Session
from flask_uploads import UploadSet, IMAGES, configure_uploads, patch_request_class

from apps.admin.views import UserModelview, KindModelview, NewModelview, CommentModelview

db = SQLAlchemy()
migrate = Migrate()


def init_db(app):
    """
    配置数据库相关信息
    :param app:
    :return:
    """
    app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:root@localhost:3306/flask_news?charset=utf8'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
    app.config['SECRET_KEY'] = 'this is the 1000phone flask secret key'
    db.init_app(app)
    migrate.init_app(app=app, db=db)


# ------------------------------Session配置--------------------------------
session = Session()


def init_session(app):
    app.config['SECRET_KEY'] = os.urandom(24)  # 密钥
    app.config['PERMANENT_SESSION_LIFETIME'] = 60 * 60
    app.config['SESSION_TYPE'] = 'redis'
    app.config['SESSION_PERMANENT'] = False  # 如果设置为True，则关闭浏览器session就失效。
    app.config['SESSION_REDIS'] = redis.Redis(host='127.0.0.1', port='6379')
    session.init_app(app)


# ------------------------------  Admin配置  --------------------------------
def init_admin(app):
    from apps.models import User, Kind, News, Comment
    app.config['BABEL_DEFAULT_LOCALE'] = 'zh_CN'
    admin = Admin(app, name='千锋新闻后台管理', template_mode='bootstrap3')
    admin.add_view(UserModelview(User, db.session, name=u'用户管理', endpoint='admin_user'))
    admin.add_view(KindModelview(Kind, db.session, name=u'标签管理', endpoint='admin_kind'))
    admin.add_view(NewModelview(News, db.session, name=u'新闻管理', endpoint='admin_new'))
    admin.add_view(CommentModelview(Comment, db.session, name=u'评论管理', endpoint='admin_comment'))
    return admin


# ------------------------------文件上传配置--------------------------------
# 获取当前文件所在的根目录
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# 获取项目上传文件的目录
UPLOAD_PATH = os.path.join(BASE_DIR, 'static/upload/HeadImg')
images = UploadSet('images', extensions=IMAGES)


def init_uploads_config(app):
    # 文件上传的路径
    app.config['UPLOADS_DEFAULT_DEST'] = UPLOAD_PATH
    # 生成图片地址的url地址 默认 http://127.0.0.1:9000/_uploads/
    app.config['UPLOADS_DEFAULT_URL'] = 'http://127.0.0.1:9000/static/upload/HeadImg'
    # 默认文件上传类型 DEFAULTS = TEXT + DOCUMENTS + IMAGES + DATA
    configure_uploads(app, images)
    # 文件上传的最大长度 默认64m
    patch_request_class(app, 16 * 1024 * 1024)


def get_file_name(old_name):
    # .png .jpg
    # 获取客服端图片的后缀名
    suffix_name = '.' + old_name.split('.')[-1]
    # 把时间类型转化指定格式的字符串输出
    # IMG20180503161930
    new_name = 'IMG_%s' % (datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
    return new_name + suffix_name
